package cn.time1024.time_app

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import com.example.timeassistant.network.RegisterRequest
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.AppUserDto
import com.example.timeassistant.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import cn.jpush.android.api.JPushInterface

class RegisterActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        val etAccount = findViewById<EditText>(R.id.etAccount)
        val etPassword = findViewById<EditText>(R.id.etPassword)
        val etNickname = findViewById<EditText>(R.id.etNickname)
        val btnRegister = findViewById<Button>(R.id.btnRegister)
        val tvMessage = findViewById<TextView>(R.id.tvMessage)

        btnRegister.setOnClickListener {
            val account = etAccount.text?.toString()?.trim().orEmpty()
            val password = etPassword.text?.toString().orEmpty()
            val nickname = etNickname.text?.toString()?.trim()
            tvMessage.text = ""

            // 获取当前设备的 JPush RegistrationID
            val rid = JPushInterface.getRegistrationID(applicationContext)

            val call = RetrofitClient.api.register(RegisterRequest(account, password, nickname, rid))
            call.enqueue(object : Callback<ResponseEnvelope<AppUserDto>> {
                override fun onResponse(
                    call: Call<ResponseEnvelope<AppUserDto>>, response: Response<ResponseEnvelope<AppUserDto>>
                ) {
                    if (!response.isSuccessful) {
                        tvMessage.text = "注册失败：${response.code()}"
                        return
                    }
                    val body = response.body()
                    if (body?.success == true || body?.code == "00000") {
                        tvMessage.text = "注册成功，请返回登录"
                    } else {
                        tvMessage.text = body?.message ?: "注册失败"
                    }
                }

                override fun onFailure(call: Call<ResponseEnvelope<AppUserDto>>, t: Throwable) {
                    tvMessage.text = "网络错误：${t.message}"
                }
            })
        }
    }
}